# -*- coding:utf-8 -*-
import glob
import json
import os, sys, time, subprocess  # ,msvcrt
import threading
from multiprocessing import pool
from multiprocessing.pool import Pool

import multiprocessing
from apptoolkit import Device
import shutil
from appium import webdriver


# 获取配置信息
def Getconfig():
    config = {"Pacname": "Pacname", "WMname": "WMname", "Yaml": "Yaml"} #config 字典
    openfile = open("./.config", mode='r')
    # 读取配置信息读行次数
    try:
        while True:
            line = openfile.readline().strip().split(":")
            # line = line.strip()  # 去除首尾空格
            # line = line.split(":")
            if line[0] == "Pacname":
                config["Pacname"] = line[1]
                print ("AppCrawler包名:%s, 读取成功" % (config["Pacname"]))
            elif line[0] == "WMname":
                config["WMname"] = line[1]
                print("外卖App包名: %s, 读取成功" % (config["WMname"]))
            elif line[0] == "Yaml":
                config["Yaml"] = line[1]
                print("配置文件名: %s, 读取成功" % (config["Yaml"]))
            else:
                break
    except:
        print("配置文件有误, 请检查")
    finally:
        openfile.close()
        print("读取配置信息成功, 即将开始遍历")
        time.sleep(3)
        return config


# 运行AppCrawlerJar 包
def Runjar(ports_number, appium_server_ports):
    startAndroid(ports_number,appium_server_ports)
    Input = Getconfig()
    # 本处输入执行命令
    Command = "java -jar %s " \
              "-c %s " \
              "-a " \
              "%s " \
              "-u %s " \
              % (Input.get("Pacname"), Input.get("Yaml"), Input.get("WMname"), appium_server_ports)
    print(Command)
    os.system(Command)


    # 重置手机链接
def reset():
    adb = "taskkill -f -t -im adb.exe"
    kadb = "taskkill -f -t -im kadb.exe"
    device = "adb devices"
    os.system(adb)
    os.system(kadb)
    os.system(device)


# 拷贝文件
def copyfiles(path, files):
    for i in files:
        shutil.copy(i, path)


def startappium():
    os.system('sh run.sh')


def startAndroid(ports_number, appium_server_ports):
    all_android_devices = Device().get_android_devices()
    android_devices = all_android_devices[ports_number-1]
    print(android_devices)
    desired_caps = {}
    desired_caps['os_version'] = android_devices['os_version']
    desired_caps['platformName'] = android_devices['os_type']
    desired_caps['os_type'] = android_devices['os_type']
    desired_caps['rom_version'] = android_devices['rom_version']
    desired_caps['deviceName'] = android_devices['model']
    desired_caps['udid'] = android_devices['uid']
    desired_caps['appPackage'] = 'com.baidu.lbs.waimai'
    desired_caps['appActivity'] = 'com.baidu.lbs.waimai.SplashActivity'
    print(desired_caps)
    driver = webdriver.Remote('http://0.0.0.0:' + str(appium_server_ports) + '/wd/hub', desired_caps)
    print('>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>')
    print(driver)

# 找到目标日志文件夹
def findTargetLogFolder():
    current_path = os.getcwd()
    foldergroup = []
    platform = "Android"
    for root, dirs, files in os.walk(current_path, topdown=False):
        for folder in dirs:
            foldername = os.path.join(root, folder)
            if platform in foldername:
                foldername = foldername.split("_")
                foldername = foldername[1].split("\\")
                foldername = foldername[0]
                foldergroup.append(foldername)

    result = max(foldergroup)
    for targetLogFolder in os.listdir("."):
        if result in targetLogFolder:
            targetLogFolder = os.path.join(os.getcwd(), targetLogFolder)
            return targetLogFolder


# 在目标日志文件夹中过滤har文件
def logFilter():
    targetLogFolder = findTargetLogFolder()
    currentpath = os.chdir(targetLogFolder)
    harfiles = glob.glob("*.har")
    # print(harfiles)
    return harfiles


# 错误日志筛选规则
def verifylog(json_str, harfile):
    entries = json_str['log']['entries']
    for response in entries:
        error_num = 0
        # 解释json
        status = response['response']['status']
        content = response['response']['content']
        mimeType = content['mimeType']
        #
        if content.get('text') == None:
            pass
        elif mimeType != "application/json":
            pass

        else:
            text = content['text']
            text_json = json.loads(text)
            # print("text_json类型:%s" %type(text_json))
            # print('error_no' in text_json.keys())
            if 'error_no' in text_json.keys() == True:
                error_no = text_json['error_no']
                print("error_no为%s" % error_no)
                if error_no == 0:
                    pass
                elif status == 200:
                    pass
                else:
                    error_num += 1
                    print("此日志有错误")
            else:
                pass
    return error_num


# 执行遍历日志文件, 进行错误日志筛选
def verifylog_exe():
    harfiles = logFilter()
    for i in harfiles:
        print("当前验证日志文件:%s" % i)
        # openfile = open("./.config", encoding='UTFmode = 'r')


        with open(i, 'r', encoding='UTF-8') as w:
            json_str = json.loads(w.readline())
            error_num = verifylog(json_str, i)
    if error_num == 0:
        print("恭喜你, 没有报错日志")
    else:
        print("共有%s处错误" % error_num)

# **  python需要开启两个线程，两台手机才能同时运行
appium_server_ports=(4500,4501,4502)
startappium()
threads=[]
for ports_number in range(1,len(appium_server_ports)):
    print(len(appium_server_ports))
    print("ports_number：" + str(ports_number))
    print("appium_server_ports[ports_number]" + str(appium_server_ports[ports_number]))
    # t0 = threading.Thread(target=Runjar, args=(ports_number,appium_server_ports[ports_number],))  #多线程：可同时启动多个应用，但不能在多个设备上运行case
    t0 = multiprocessing.Process(target=Runjar, args=(ports_number,appium_server_ports[ports_number],)) #多进程：
    threads.append(t0)
print(threads)

if __name__ == '__main__':
    threadLock = threading.Lock()
    for t in threads:
        threadLock.acquire()
        print(t)
        t.start()
        threadLock.release()
    for t in  threads:
        t.join()



